<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="检验单号" prop="inspectionCode">
        <el-input v-model="queryParams.inspectionCode" placeholder="请输入检验单号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="项目编码" prop="itemCode">
        <el-input v-model="queryParams.itemCode" placeholder="请输入检验项目编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="项目名称" prop="itemName">
        <el-input v-model="queryParams.itemName" placeholder="请输入检验项目名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="结果" prop="conclusion">
        <el-select v-model="queryParams.conclusion" placeholder="请选择结果" clearable>
          <el-option label="合格" value="合格" />
          <el-option label="不合格" value="不合格" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['quality:inspectionItem:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['quality:inspectionItem:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['quality:inspectionItem:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['quality:inspectionItem:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="inspectionItemList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="记录ID" align="center" prop="recordId" />
      <el-table-column label="检验记录ID" align="center" prop="inspectionId" />
      <el-table-column label="检验单号" align="center" prop="inspectionCode" />
      <el-table-column label="检验项目ID" align="center" prop="itemId" />
      <el-table-column label="检验项目编码" align="center" prop="itemCode" />
      <el-table-column label="检验项目名称" align="center" prop="itemName" />
      <el-table-column label="检验值" align="center" prop="inspectionValue" />
      <el-table-column label="结果" align="center" prop="conclusion">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.conclusion == '合格'" type="success">合格</el-tag>
          <el-tag v-else type="danger">不合格</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['quality:inspectionItem:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['quality:inspectionItem:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改检验项目记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 关联信息 -->
        <el-divider content-position="left">关联信息</el-divider>
        <el-row>
          <el-col :span="24">
            <el-form-item label="检验记录" prop="inspectionId">
              <el-select v-model="form.inspectionId" placeholder="请选择检验记录" @change="handleInspectionChange" clearable style="width: 100%">
                <el-option v-for="inspection in inspectionList" :key="inspection.inspectionId" :label="inspection.inspectionCode" :value="inspection.inspectionId">
                  <span style="float: left">{{ inspection.inspectionCode }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ inspection.productName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="检验项目" prop="itemId">
              <el-select v-model="form.itemId" placeholder="请选择检验项目" @change="handleItemChange" clearable style="width: 100%">
                <el-option v-for="item in itemList" :key="item.itemId" :label="item.itemName" :value="item.itemId">
                  <span style="float: left">{{ item.itemName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.itemCode }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 自动填充信息 -->
        <el-divider content-position="left">项目信息</el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目编码" prop="itemCode">
              <el-input v-model="form.itemCode" placeholder="自动填充" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="itemName">
              <el-input v-model="form.itemName" placeholder="自动填充" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 检验结果 -->
        <el-divider content-position="left">检验结果</el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="检验值" prop="inspectionValue">
              <el-input v-model="form.inspectionValue" placeholder="请输入检验值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结果" prop="conclusion">
              <el-select v-model="form.conclusion" placeholder="请选择结果">
                <el-option label="合格" value="合格" />
                <el-option label="不合格" value="不合格" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInspectionItem, getInspectionItem, delInspectionItem, addInspectionItem, updateInspectionItem } from "@/api/mes/quality/inspectionitem";
import { listInspection } from "@/api/mes/quality/inspection";
import { listItem } from "@/api/mes/quality/item";

export default {
  name: "InspectionItem",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 检验项目记录表格数据
      inspectionItemList: [],
      // 检验记录列表
      inspectionList: [],
      // 检验项目列表
      itemList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        inspectionCode: null,
        itemCode: null,
        itemName: null,
        conclusion: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        inspectionId: [
          { required: true, message: "检验记录ID不能为空", trigger: "blur" }
        ],
        itemId: [
          { required: true, message: "检验项目ID不能为空", trigger: "blur" }
        ],
        inspectionValue: [
          { required: true, message: "检验值不能为空", trigger: "blur" }
        ],
        conclusion: [
          { required: true, message: "结果不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getInspectionList();
    this.getItemList();
  },
  methods: {
    /** 查询检验项目记录列表 */
    getList() {
      this.loading = true;
      listInspectionItem(this.queryParams).then(response => {
        this.inspectionItemList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        recordId: null,
        inspectionId: null,
        inspectionCode: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        inspectionValue: null,
        conclusion: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.recordId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加检验项目记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const recordId = row.recordId || this.ids
      getInspectionItem(recordId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改检验项目记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.recordId != null) {
            updateInspectionItem(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInspectionItem(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const recordIds = row.recordId || this.ids;
      this.$modal.confirm('是否确认删除检验项目记录编号为"' + recordIds + '"的数据项？').then(function () {
        return delInspectionItem(recordIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('quality/inspectionItem/export', {
        ...this.queryParams
      }, `inspectionItem_${new Date().getTime()}.xlsx`)
    },
    
    /** 获取检验记录列表 */
    getInspectionList() {
      // 需要导入对应的API
      // import { listInspection } from "@/api/mes/quality/inspection";
      listInspection({}).then(response => {
        this.inspectionList = response.rows || [];
      });
    },
    
    /** 获取检验项目列表 */
    getItemList() {
      // 需要导入对应的API
      // import { listItem } from "@/api/mes/quality/item";
      listItem({}).then(response => {
        this.itemList = response.rows || [];
      });
    },
    
    /** 检验记录选择变化处理 */
    handleInspectionChange(inspectionId) {
      if (inspectionId) {
        const selectedInspection = this.inspectionList.find(i => i.inspectionId === inspectionId);
        if (selectedInspection) {
          this.form.inspectionCode = selectedInspection.inspectionCode;
        }
      } else {
        this.form.inspectionCode = '';
      }
    },
    
    /** 检验项目选择变化处理 */
    handleItemChange(itemId) {
      if (itemId) {
        const selectedItem = this.itemList.find(i => i.itemId === itemId);
        if (selectedItem) {
          this.form.itemCode = selectedItem.itemCode;
          this.form.itemName = selectedItem.itemName;
        }
      } else {
        this.form.itemCode = '';
        this.form.itemName = '';
      }
    }
  }
};
</script>